<!-- 家教管理页面 -->
<template>
    <div class="tutoring-manage">
        <el-tabs v-model="activeTab">
            <el-tab-pane label="我的家教" name="tutoring">
                <el-table :data="tutorings" style="width: 100%">
                    <el-table-column prop="title" label="标题" />
                    <el-table-column prop="subjects" label="科目" />
                    <el-table-column prop="targetLevel" label="适合层次" />
                    <el-table-column prop="hourlyRate" label="课时费">
                        <template #default="scope">
                            ¥{{ scope.row.hourlyRate }}/小时
                        </template>
                    </el-table-column>
                    <el-table-column prop="status" label="状态">
                        <template #default="scope">
                            <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
                                {{ scope.row.status === 1 ? '已发布' : '已下架' }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="200">
                        <template #default="scope">
                            <el-button
                                :type="scope.row.status === 1 ? 'warning' : 'success'"
                                size="small"
                                @click="handleStatusChange(scope.row)"
                            >
                                {{ scope.row.status === 1 ? '下架' : '发布' }}
                            </el-button>
                            <el-button
                                type="primary"
                                size="small"
                                @click="handleEdit(scope.row)"
                            >
                                编辑
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>

            <el-tab-pane label="预约管理" name="booking">
                <el-table :data="bookings" style="width: 100%">
                    <el-table-column width="80">
                        <template #default="scope">
                            <el-avatar :src="scope.row.studentAvatar" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="studentName" label="学生" />
                    <el-table-column prop="tutoringTitle" label="家教课程" />
                    <el-table-column label="预约时间">
                        <template #default="scope">
                            {{ formatDateTime(scope.row.startTime) }} 至 {{ formatDateTime(scope.row.endTime) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="location" label="上课地点" />
                    <el-table-column prop="status" label="状态">
                        <template #default="scope">
                            <el-tag :type="getBookingStatusType(scope.row.status)">
                                {{ getBookingStatusText(scope.row.status) }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="200">
                        <template #default="scope">
                            <el-button
                                v-if="scope.row.status === 0"
                                type="success"
                                size="small"
                                @click="handleBooking(scope.row.id, 1)"
                            >
                                接受
                            </el-button>
                            <el-button
                                v-if="scope.row.status === 0"
                                type="danger"
                                size="small"
                                @click="handleBooking(scope.row.id, 2)"
                            >
                                拒绝
                            </el-button>
                            <el-button
                                v-if="scope.row.status === 1"
                                type="primary"
                                size="small"
                                @click="handleBooking(scope.row.id, 3)"
                            >
                                完成
                            </el-button>
                            <el-button
                                v-if="scope.row.status === 3"
                                type="danger"
                                size="small"
                                @click="deleteBooking(scope.row.id)"
                            >
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
        </el-tabs>

        <!-- 编辑对话框 -->
        <el-dialog v-model="dialogVisible" title="编辑家教信息" width="50%">
            <el-form :model="editForm" :rules="rules" ref="editFormRef" label-width="120px">
                <el-form-item label="标题" prop="title">
                    <el-input v-model="editForm.title"></el-input>
                </el-form-item>
                <el-form-item label="描述" prop="description">
                    <el-input type="textarea" v-model="editForm.description"></el-input>
                </el-form-item>
                <el-form-item label="可授科目" prop="subjects">
                    <el-select v-model="editForm.subjects" multiple>
                        <el-option
                            v-for="subject in subjects"
                            :key="subject"
                            :label="subject"
                            :value="subject"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="适合层次" prop="targetLevel">
                    <el-select v-model="editForm.targetLevel">
                        <el-option
                            v-for="level in targetLevels"
                            :key="level"
                            :label="level"
                            :value="level"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="课时费" prop="hourlyRate">
                    <el-input-number v-model="editForm.hourlyRate" :min="0" :precision="2"></el-input-number>
                </el-form-item>
                <el-form-item label="授课方式" prop="teachingMethod">
                    <el-radio-group v-model="editForm.teachingMethod">
                        <el-radio label="线下">线下</el-radio>
                        <el-radio label="线上">线上</el-radio>
                        <el-radio label="均可">均可</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="授课地点" prop="location">
                    <el-input v-model="editForm.location"></el-input>
                </el-form-item>
                <el-form-item label="可用时间" prop="availableTime">
                    <el-input type="textarea" v-model="editForm.availableTime"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitEdit">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { tutoringService } from '@/api/tutoring'

const activeTab = ref('tutoring')
const tutorings = ref([])
const bookings = ref([])
const dialogVisible = ref(false)
const editFormRef = ref(null)
const editForm = ref({
    id: null,
    title: '',
    description: '',
    subjects: [],
    targetLevel: '',
    hourlyRate: 0,
    teachingMethod: '',
    location: '',
    availableTime: ''
})

// 科目列表
const subjects = [
    '语文', '数学', '英语', '物理', '化学', '生物',
    '政治', '历史', '地理', '音乐', '美术', '体育'
]

// 适合层次
const targetLevels = [
    '小学', '初中', '高中', '大学', '考研', '出国'
]

// 表单验证规则
const rules = {
    title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
    description: [{ required: true, message: '请输入描述', trigger: 'blur' }],
    subjects: [{ required: true, message: '请选择可授科目', trigger: 'change' }],
    targetLevel: [{ required: true, message: '请选择适合层次', trigger: 'change' }],
    hourlyRate: [{ required: true, message: '请输入课时费', trigger: 'blur' }],
    teachingMethod: [{ required: true, message: '请选择授课方式', trigger: 'change' }],
    location: [{ required: true, message: '请输入授课地点', trigger: 'blur' }],
    availableTime: [{ required: true, message: '请输入可用时间', trigger: 'blur' }]
}

// 获取教师的家教信息
const getTeacherTutoring = async () => {
    try {
        const response = await tutoringService.getTeacherTutoring()
        tutorings.value = response.data
    } catch (error) {
        ElMessage.error('获取家教信息失败')
    }
}

// 获取教师的预约信息
const getTeacherBookings = async () => {
    try {
        const response = await tutoringService.getTeacherBookings()
        bookings.value = response.data
    } catch (error) {
        ElMessage.error('获取预约信息失败')
    }
}

// 处理状态变更
const handleStatusChange = async (row) => {
    try {
        const newStatus = row.status === 1 ? 0 : 1
        await tutoringService.updateTutoringStatus(row.id, newStatus)
        ElMessage.success(newStatus === 1 ? '发布成功' : '下架成功')
        getTeacherTutoring()
    } catch (error) {
        ElMessage.error('操作失败')
    }
}

// 处理编辑
const handleEdit = (row) => {
    editForm.value = {
        ...row,
        subjects: row.subjects.split(',')
    }
    dialogVisible.value = true
}

// 提交编辑
const submitEdit = async () => {
    if (!editFormRef.value) return
    
    await editFormRef.value.validate(async (valid) => {
        if (valid) {
            try {
                const submitData = {
                    ...editForm.value,
                    subjects: editForm.value.subjects.join(',')
                }
                await tutoringService.updateTutoring(submitData)
                ElMessage.success('更新成功')
                dialogVisible.value = false
                getTeacherTutoring()
            } catch (error) {
                ElMessage.error('更新失败')
            }
        }
    })
}

// 处理预约
const handleBooking = async (id, status) => {
    try {
        const action = status === 1 ? '接受' : status === 2 ? '拒绝' : '完成'
        await ElMessageBox.confirm(`确定要${action}这个预约吗？`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
        
        await tutoringService.handleBooking(id, status)
        ElMessage.success(`${action}成功`)
        getTeacherBookings()
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('操作失败')
        }
    }
}

// 获取预约状态类型
const getBookingStatusType = (status) => {
    switch (status) {
        case 0: return 'warning'
        case 1: return 'success'
        case 2: return 'danger'
        case 3: return 'info'
        default: return 'info'
    }
}

// 获取预约状态文本
const getBookingStatusText = (status) => {
    switch (status) {
        case 0: return '待确认'
        case 1: return '已接受'
        case 2: return '已拒绝'
        case 3: return '已完成'
        default: return '未知'
    }
}

// 格式化日期时间
const formatDateTime = (datetime) => {
    if (!datetime) return ''
    
    // 处理ISO 8601格式的字符串（带T和Z的格式）
    let date;
    
    if (typeof datetime === 'string') {
        // 检查是否包含'T'但不包含时区信息
        if (datetime.includes('T') && !datetime.includes('Z') && !datetime.includes('+')) {
            // 添加'Z'表示这是UTC时间，让浏览器正确转换为本地时间
            date = new Date(datetime + 'Z');
        } else {
            date = new Date(datetime);
        }
    } else {
        date = new Date(datetime);
    }
    
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 删除预约
const deleteBooking = async (id) => {
    try {
        await ElMessageBox.confirm('确定要删除这个已完成的预约吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
        
        await tutoringService.deleteBooking(id)
        ElMessage.success('删除成功')
        getTeacherBookings()
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('删除失败')
        }
    }
}

onMounted(() => {
    getTeacherTutoring()
    getTeacherBookings()
})
</script>

<style scoped>
.tutoring-manage {
    padding: 20px;
}

.el-select {
    width: 100%;
}

.el-avatar {
    margin-right: 10px;
}
</style> 